/*
 * This file is part of the EasyFlash Library.
 *
 * Copyright (c) 2015-2019, Armink, <armink.ztl@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * 'Software'), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Function: Portable interface for each platform.
 * Created on: 2015-01-16
 */
#include <easyflash.h>
#include <rtthread.h>
#include "dma.h"
#include "uni_hal_mailbox.h"
#include "uni_iot.h"
#define FLASH_PRINT(format, ...)	 		//rt_kprintf("616:%s %d:"format, __FUNCTION__, __LINE__, ##__VA_ARGS__)

#define EF_PORT_REGION_OFFSET  (EF_START_ADDR)
#define EF_PORT_REGION_SIZE    (ENV_AREA_SIZE)

#define EF_PORT_R    				(1UL)
#define EF_PORT_W    				(2UL)
#define EF_PORT_E    				(3UL)

static rt_mutex_t env_cache_lock;

/* default environment variables set for user */
static const ef_env default_env_set[] = {

};
static rt_sem_t s_ef_port_sem = RT_NULL;
static uint32_t s_ef_port_init = 0;
static uint32_t s_ef_port_result;

static int ef_port_flash_rw_done_callback(char *args, mailbox_message *message)
{
	//FLASH_PRINT("%x\t%x\t%x\t%x\t%x\t%x\t%x\t%x\n", 
		//message->sequenceId, message->taskId, message->size, message->data[0],
		//message->data[1], message->data[2], message->data[3], message->data[4]);
	if(message->taskId == MAILBOX_EASYFLASH){
		//rw_done_msg.data[1] = offset;
		//rw_done_msg.data[2] = len;
		//rw_done_msg.data[3] = ret_rw_result;
		s_ef_port_result = message->data[3];
		rt_sem_release(s_ef_port_sem);
	}
	return 0;
}

static int32_t ef_port_flash_init(void)
{	
	FLASH_PRINT("\n");
	if(s_ef_port_init == 1){
		FLASH_PRINT("already inited\n");
		return 0;
	}
	sys_hal_mailbox_register_callback(MAILBOX_EASYFLASH, ef_port_flash_rw_done_callback, NULL);
	s_ef_port_sem = rt_sem_create("s_ef_port_sem", 0, RT_IPC_FLAG_FIFO);
	if(RT_NULL == s_ef_port_sem){
		FLASH_PRINT("rt_sem_create s_ef_port_sem failed\n");
		return -1;
	}
	s_ef_port_init = 1;
	return 0;
}

static int32_t ef_port_flash_erase(uint32_t offset,uint32_t len)
{
	rt_err_t retval;
	mailbox_message flash_cfg_msg = {0};
	if((offset + len) > (EF_PORT_REGION_OFFSET + EF_PORT_REGION_SIZE)){
		FLASH_PRINT("illegal offset = 0x%x, len = 0x%x\n", offset, len);
		return -1;
	}

	flash_cfg_msg.taskId = MAILBOX_EASYFLASH;
	flash_cfg_msg.data[0] = EF_PORT_E;
	flash_cfg_msg.data[1] = offset;
	flash_cfg_msg.data[2] = 0;
	flash_cfg_msg.data[3] = (int)len;
	
	sys_hal_mailbox_send(&flash_cfg_msg);
	retval = rt_sem_take(s_ef_port_sem, RT_WAITING_FOREVER);
	if(RT_EOK != retval){
		FLASH_PRINT("erase failed, take sem failed, retval = %d\n", retval);
		return -1;
	}
	return s_ef_port_result;
}

static int32_t ef_port_flash_read(uint8_t *buff, uint32_t offset,uint32_t len)
{
	rt_err_t retval;
	mailbox_message readmsg = {0};
	if((offset + len) > (EF_PORT_REGION_OFFSET + EF_PORT_REGION_SIZE)){
		FLASH_PRINT("illegal offset = 0x%x, len = 0x%x\n", offset, len);
		return -1;
	}
	if(len > EASYCONFIG_LENGTH){
		FLASH_PRINT("illegal len = 0x%x, EASYCONFIG_LENGTH = 0x%x\n", len, EASYCONFIG_LENGTH);
		return -1;
	}
	readmsg.taskId = MAILBOX_EASYFLASH;
	readmsg.data[0] = EF_PORT_R;
	readmsg.data[1] = offset;
	readmsg.data[2] = (uint32_t)EASYCONFIG_ADDR;
	readmsg.data[3] = len;

	sys_hal_mailbox_send(&readmsg);
	retval = rt_sem_take(s_ef_port_sem, RT_WAITING_FOREVER);
	if(RT_EOK != retval){
		FLASH_PRINT("erase failed, take sem failed, retval = %d\n", retval);
		return -1;
	}

	if(len != s_ef_port_result){
		return -1;
	}
	memcpy(buff, (const void *)EASYCONFIG_ADDR, s_ef_port_result);
	return s_ef_port_result;
}

static int32_t ef_port_flash_write(uint8_t *buff, uint32_t offset,uint32_t len)
{
	rt_err_t retval;
	mailbox_message writemsg = {0};
	FLASH_PRINT("\n");
	if((offset + len) > (EF_PORT_REGION_OFFSET + EF_PORT_REGION_SIZE)){
		FLASH_PRINT("illegal offset = 0x%x, len = 0x%x\n", offset, len);
		return -1;
	}
	if(len > EASYCONFIG_LENGTH){
		FLASH_PRINT("illegal len = 0x%x, EASYCONFIG_LENGTH = 0x%x\n", len, EASYCONFIG_LENGTH);
		return -1;
	}
	memcpy((void *)EASYCONFIG_ADDR, buff, len);	
	writemsg.taskId = MAILBOX_EASYFLASH;
	writemsg.data[0] = EF_PORT_W;
	writemsg.data[1] = offset;
	writemsg.data[2] = (uint32_t)EASYCONFIG_ADDR;
	writemsg.data[3] = len;
	
	sys_hal_mailbox_send(&writemsg);
	retval = rt_sem_take(s_ef_port_sem, RT_WAITING_FOREVER);
	if(RT_EOK != retval){
		FLASH_PRINT("erase failed, take sem failed, retval = %d\n", retval);
		return -1;
	}
	return s_ef_port_result;
}


/**
 * Flash port for hardware initialize.
 *
 * @param default_env default ENV set for user
 * @param default_env_size default ENV size
 *
 * @return result
 */
EfErrCode ef_port_init(ef_env const **default_env, size_t *default_env_size) {

    EfErrCode result = EF_NO_ERR;
    *default_env = default_env_set;
    *default_env_size = sizeof(default_env_set) / sizeof(default_env_set[0]);

    env_cache_lock = rt_mutex_create("mutex", RT_IPC_FLAG_FIFO);
	result = ef_port_flash_init();
    return result;
}

/**
 * Read data from flash.
 * @note This operation's units is word.
 *
 * @param addr flash address
 * @param buf buffer to store read data
 * @param size read bytes size
 *
 * @return result
 */
EfErrCode ef_port_read(uint32_t addr, uint32_t *buf, size_t size) {
    EfErrCode result = EF_NO_ERR;
	uint8_t *buf_8 = (uint8_t *)buf;
	int ret;
	//fLib_printf("read addr is 0x%x,size is %d\n",addr,size);

	EF_ASSERT(size % 4 == 0);
	ret = ef_port_flash_read(buf_8, addr, size);
	if(ret<0){
		FLASH_PRINT("ef_port_read failed, ret = %d\n", ret);
		 result = EF_READ_ERR;
	}
    return result;
}

/**
 * Erase data on flash.
 * @note This operation is irreversible.
 * @note This operation's units is different which on many chips.
 *
 * @param addr flash address
 * @param size erase bytes size
 *
 * @return result
 */
EfErrCode ef_port_erase(uint32_t addr, size_t size) {
    EfErrCode result = EF_NO_ERR;	
	int ret;  
	
    ret = ef_port_flash_erase(addr, size);
    if(ret<0){
		 result = EF_ERASE_ERR;
	}

    return result;
}
/**
 * Write data to flash.
 * @note This operation's units is word.
 * @note This operation must after erase. @see flash_erase.
 *
 * @param addr flash address
 * @param buf the write data buffer
 * @param size write bytes size
 *
 * @return result
 */
EfErrCode ef_port_write(uint32_t addr, const uint32_t *buf, size_t size) {
    EfErrCode result = EF_NO_ERR;  
    /* You can add your code under here. */
	uint8_t *buf_8 = (uint8_t *)buf;
	int ret;
	//fLib_printf("write addr is 0x%x,size is %d\n",addr,size);
	
	EF_ASSERT(size % 4 == 0);
	
    ret = ef_port_flash_write(buf_8, addr, size);
    if(ret<0){
		FLASH_PRINT("ef_port_write failed, ret = %d\n", ret);
		 result = EF_WRITE_ERR;
	}
    return result;
}

/**
 * lock the ENV ram cache
 */
void ef_port_env_lock(void) {
    
	rt_mutex_take(env_cache_lock, RT_WAITING_FOREVER);
}

/**
 * unlock the ENV ram cache
 */
void ef_port_env_unlock(void) {
    
    rt_mutex_release(env_cache_lock);
}


/**
 * This function is print flash debug info.
 *
 * @param file the file which has call this function
 * @param line the line number which has call this function
 * @param format output format
 * @param ... args
 *
 */
void ef_log_debug(const char *file, const long line, const char *format, ...) {


}

/**
 * This function is print flash routine info.
 *
 * @param format output format
 * @param ... args
 */
void ef_log_info(const char *format, ...) {
#ifdef PRINT_DEBUG
    va_list args;

    /* args point to the first variable parameter */
    va_start(args, format);

    /* You can add your code under here. */
    
    va_end(args);
#endif
}
/**
 * This function is print flash non-package info.
 *
 * @param format output format
 * @param ... args
 */
void ef_print(const char *format, ...) {
#ifdef PRINT_DEBUG
    va_list args;

    /* args point to the first variable parameter */
    va_start(args, format);

    /* You can add your code under here. */
    
    va_end(args);
#endif
}
